package com.us.usws.site.ipodium.action;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.us.usws.biz.ResourceStorageReplacer;
import com.us.usws.service.cud.UserCUDService;
import com.us.usws.support.uitls.ServiceFactory;
import com.us.usws.support.uitls.SiteWebContext;

@WebServlet(asyncSupported = true, name = "fileUpload", urlPatterns = "/ipodium/uploadAvatar")
@MultipartConfig
public class IpodiumAvatarUploadServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	private static Log log = LogFactory.getFactory().getInstance(IpodiumAvatarUploadServlet.class);

	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();

		String type = request.getParameter("type");
		String ext = request.getParameter("ext");
		log.info("Got type=[" + type + "], ext=[" + ext + "].");

		//get file part
		Part part = request.getPart("userFile");
		log.info("contentType:[" + part.getContentType() + "], size=[" + part.getSize() + "].");

		//writedown
		SiteWebContext swc = new SiteWebContext(request, response);
		String userUid = swc.getIpodiumUser().getUid();
		String avatar = userUid + "." + ext.toLowerCase();
		String storeDir = ResourceStorageReplacer.getUserDir(userUid);
		String storePath = ResourceStorageReplacer.getUserAvatarPath(userUid, avatar);
		//save
		File f = new File(storeDir);
		if (!f.exists()) {
			f.mkdirs();
		}
		log.info("Store file to [" + f.getAbsolutePath() + "].");
		part.write(storePath);

		//update
		UserCUDService service = ServiceFactory.getInstance().getService(UserCUDService.class);
		service.updateAvatar(userUid, avatar);
		out.print(true);
	}
}
